package com.scyshkj.university.wechat.wanxiao;

import com.scyshkj.university.wechat.ApplicationProperties;
import com.scyshkj.university.wechat.pay.WechatLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by 唐旭 on 2016/11/18.
 */
@Controller
@RequestMapping("/wanxiao/login")
public class WanxiaoAuthLoginController {

    @Autowired
    private WanxiaoLoginService loginService;
    @Autowired
    private WechatLoginService wechatLoginService;
    @Autowired
    private ApplicationProperties applicationProperties;

    @RequestMapping
    public String login(String code, HttpServletRequest request) {
        //未授权或者授权失败
        if (StringUtils.isEmpty(code)) {
            return "redirect:/unauthorized.html";
        }

        //玩笑OAuth登录
        String message = loginService.login(code);
        if (!StringUtils.isEmpty(message)) {
            return "redirect:/unauthorized.html";
        }
        //已登录微信
        if (StringUtils.isEmpty(message) && wechatLoginService.isLogin()) {
            return "redirect:" + applicationProperties.getIndexUrl();
        }
        //未登录微信
        if (StringUtils.isEmpty(message) && !wechatLoginService.isLogin()) {
            return "redirect:" + wechatLoginService.getLoginUrl(request);
        }
        return "redirect:/unauthorized.html";
    }
}
